package com.huaxindata.im.main.contactview.friend;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxindata.im.R;
import com.huaxindata.im.R2;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.main.chat.ConversationActivity;
import com.huaxindata.im.main.chat.ConversationManager;
import com.huaxindata.im.main.contactview.friend.model.UserModel;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactLocal;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.contact.UserMessage;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author songxf
 * @date 2017/12/14
 * @Desc 个人中心界面
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxPersonalCenterActivity extends BaseActivity {
    @BindView(R2.id.toolbar)
    Toolbar         mToolbar;
    @BindView(R2.id.nickname_tv)
    TextView        mNicknameTv;
    @BindView(R2.id.header_img)
    AvatarImageView mHeaderImg;
    @BindView(R2.id.company_tv)
    TextView        mCompanyTv;
    @BindView(R2.id.email_tv)
    TextView        mEmailTv;
    @BindView(R2.id.email_img)
    ImageView       mEmailImg;
    @BindView(R2.id.cardview)
    CardView        mCardview;
    @BindView(R2.id.line_view)
    View            mLineView;
    @BindView(R2.id.user_phone_tv)
    TextView        mUserPhoneTv;
    @BindView(R2.id.phone_rl)
    RelativeLayout  mPhoneRl;
    @BindView(R2.id.send_msg_tv)
    TextView        mSendMsgTv;
    @BindView(R2.id.send_msg_rl)
    RelativeLayout  mSendMsgRl;
    @BindView(R2.id.bottom_rl)
    RelativeLayout  mBottomRl;
    @BindView(R2.id.company_name_tv)
    TextView        mCompanyNameTv;
    @BindView(R2.id.user_name_tv)
    TextView        mUserNameTv;
    @BindView(R2.id.phone_tv)
    TextView        mPhoneTv;
    @BindView(R2.id.user_email_tv)
    TextView        mUserEmailTv;
    @BindView(R2.id.user_department_tv)
    TextView        mUserDepartmentTv;
    @BindView(R2.id.user_position_tv)
    TextView        mUserPositionTv;
    @BindView(R2.id.user_info_lv)
    LinearLayout    mUserInfoLv;

    private String      mClientId;
    private UserMessage mUserMessage;
    private Contact     mContact;

    private int FLAG_BTN_START = 0;//临时_按钮状态
    private Resources mResources;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        //界面跳转很多只传contact
        mContact = extras.getParcelable("contact");
        //发现模块中传的id
        mClientId = extras.getString(ImConstants.CLIENT_ID);
        if (mClientId == null && mContact != null) {
            mClientId = mContact.getClientId();
        }
    }


    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        setSupportActionBar(mToolbar);
        mResources = this.getResources();
    }

    @Override
    public void initData() {
        if (!TextUtils.isEmpty(mClientId)) {//邀请好友
            if (UserManager.getClientId().equals(mClientId)) {
                setDrawableToText(true, "发消息");
            } else {
                setDrawableToText(false, "发消息");
            }
            FLAG_BTN_START = 1;
        }
        if (mContact != null) {
            updateLoadStatus(LOAD_SUCCESS);
            onContactBindData2(mContact);
        }
    }


    @Override
    protected void requestData() {
        if (!TextUtils.isEmpty(mClientId) && mContact == null) {
            updateLoadStatus(LOADING);
            setUserInfo(mClientId);
        }
    }

    /**
     * 获取用户信息
     *
     * @param clientId
     */
    public void setUserInfo(String clientId) {
        Call<UserMessage> call = RetrofitClient.getHttpApi().getUserById(clientId);
        autoClose(call);
        call.enqueue(new Callback<UserMessage>() {
            @Override
            public void onResponse(Call<UserMessage> call, Response<UserMessage> response) {
                mUserMessage = response.body();
                if (response.isSuccessful() && mUserMessage != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    //setIsRegister(mUserMessage.getPhone());
                    onIdBindData(mUserMessage);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<UserMessage> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }

    /**
     * 根据手机号查询是不是注册过的人，可能是游客或者是企业用户
     *
     * @param phonenumber
     */
    public void setIsRegister(String phonenumber) {
        Call<UserModel> call = RetrofitClient.getHttpApi().findFriendByPhone(phonenumber);

        call.enqueue(new Callback<UserModel>() {
            @Override
            public void onResponse(Call<UserModel> call, Response<UserModel> response) {
                UserModel user = response.body();
                if (response.isSuccessful() && user != null) {

                    if (user.getState() == 1) {
                        if (UserManager.getClientId().equals(user.getUserId() + "")) {
                            setDrawableToText(true, "发消息");
                        } else {
                            setDrawableToText(false, "发消息");
                        }
                        FLAG_BTN_START = 1;
                    } else {
                        setDrawableToText(null, "邀请好友");
                        mUserInfoLv.setVisibility(View.INVISIBLE);
                        FLAG_BTN_START = 2;
                    }
                } else {
                    // updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<UserModel> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }

    /**
     * 设置图片和文字
     *
     * @param text
     */
    @SuppressLint("ResourceType")
    public void setDrawableToText(Boolean isSelf, String text) {
        if (isSelf == null) {
            Drawable drawable = getResources().getDrawable(R.mipmap.person_invite);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mSendMsgTv.setCompoundDrawables(drawable, null, null, null);
            mSendMsgTv.setText(text);
            Drawable drawable1 = getResources().getDrawable(R.mipmap.person_phone_green);
            drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
            mUserPhoneTv.setCompoundDrawables(drawable1, null, null, null);
            return;
        }

        if (isSelf) {
            Drawable drawable = getResources().getDrawable(R.mipmap.person_email_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mSendMsgTv.setCompoundDrawables(drawable, null, null, null);
            mSendMsgTv.setText(text);
            Drawable drawable1 = getResources().getDrawable(R.mipmap.person_phone_icon);
            drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
            mUserPhoneTv.setCompoundDrawables(drawable1, null, null, null);
            //都不可点击
            mSendMsgRl.setBackgroundResource(R.color.divider);
            mPhoneRl.setBackgroundResource(R.color.divider);
            mSendMsgTv.setTextColor(getResources().getColor(R.color.edit_hit_color));
            mUserPhoneTv.setTextColor(getResources().getColor(R.color.edit_hit_color));
            mSendMsgRl.setClickable(false);
            mPhoneRl.setClickable(false);
            mBottomRl.setClickable(false);
        } else {
            Drawable drawable = getResources().getDrawable(R.mipmap.person_email_yellow);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mSendMsgTv.setCompoundDrawables(drawable, null, null, null);
            mSendMsgTv.setText(text);
            Drawable drawable1 = getResources().getDrawable(R.mipmap.person_phone_green);
            drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
            mUserPhoneTv.setCompoundDrawables(drawable1, null, null, null);
        }
    }

    /**
     * 根据id绑定数据
     *
     * @param userMessage
     */
    private void onIdBindData(UserMessage userMessage) {
        //昵称
        loadText(mNicknameTv, userMessage.getNickName(), "暂无");
        //公司名称
        loadText(mCompanyTv, userMessage.getCompany(), "暂无");
        //邮箱
        loadText(mEmailTv, "", "暂无");
        //头像
        HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
        instance.setHeadImage(this, userMessage.getImg(), userMessage.getNickName(), mHeaderImg);
        //公司名称2
        loadText(mCompanyNameTv, userMessage.getCompany(), "暂无");
        //昵称2
        loadText(mUserNameTv, userMessage.getNickName(), "暂无");
        //电话号码
        loadText(mPhoneTv, userMessage.getPhone(), "暂无");
        //邮箱2
        loadText(mUserEmailTv, "", "暂无");
        //部门名称
        loadText(mUserDepartmentTv, "", "暂无");
        //职位名称
        loadText(mUserPositionTv, userMessage.getTitle(), "暂无");
    }

    /**
     * 根据contact绑定数据
     *
     * @param contact
     */
    private void onContactBindData2(Contact contact) {
        //昵称
        loadText(mNicknameTv, contact.getNickName(), "暂无");
        //公司名称
        loadText(mCompanyTv, contact.getCompany(), "暂无");
        //邮箱
        loadText(mEmailTv, "", "暂无");
        //头像
        HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
        instance.setHeadImage(this, contact.getIcon(), contact.getNickName(), mHeaderImg);
        //公司名称2
        loadText(mCompanyNameTv, contact.getCompany(), "暂无");
        //昵称2
        loadText(mUserNameTv, contact.getNickName(), "暂无");
        //电话号码
        loadText(mPhoneTv, contact.getPhone(), "暂无");
        //邮箱2
        loadText(mUserEmailTv, "", "暂无");
        //部门名称
        loadText(mUserDepartmentTv, "", "暂无");
        //职位名称
        loadText(mUserPositionTv, contact.getDuty(), "暂无");
        setIsRegister(contact.getPhone());
    }

    @OnClick(R2.id.send_msg_rl)//发消息
    public void onViewClicked1(View view) {

        sendMsg();
    }

    /**
     * 发送消息
     */
    private void sendMsg() {

        if (!TextUtils.isEmpty(mClientId) && mContact == null) {
            ContactPerson contactPerson = new ContactPerson(mClientId, mUserMessage.getNickName(), mUserMessage.getImg());
            Intent intent = new Intent(HxPersonalCenterActivity.this, ConversationActivity.class);
            ConversationManager.setChatObject(contactPerson);
            HxPersonalCenterActivity.this.startActivity(intent);
        }
        if (mContact == null)
            return;
        if (mContact instanceof ContactPerson) {
            Intent intent = new Intent(HxPersonalCenterActivity.this, ConversationActivity.class);
            ConversationManager.setChatObject(mContact);
            HxPersonalCenterActivity.this.startActivity(intent);
        }
        //如果是本地联系人就打开短信界面
        if (mContact instanceof ContactLocal) {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mContact.getPhone()));
            intent.putExtra("sms_body", mResources.getString(R.string.sms_body));
            HxPersonalCenterActivity.this.startActivity(intent);
        }
    }

    @OnClick(R2.id.bottom_rl)//打电话
    public void onViewClicked2(View view) {
        if (!TextUtils.isEmpty(mClientId) && mUserMessage != null) {
            callPhone(mUserMessage.getPhone());
        } else if (mContact != null) {
            callPhone(mContact.getPhone());
        }else{
            ToastUtil.showToast("该用户暂无联系方式");
        }
    }

    //调用系统打电话功能
    public void callPhone(String phone) {
        if (!com.huaxin.common.utils.Util.checkNull(phone)) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "需授权", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intentPhone = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
            this.startActivity(intentPhone);
        }else{
            ToastUtil.showToast("该用户暂无联系方式");
        }
    }
}
